﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;

using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.PowerShell;

namespace Mystery.SharePoint.PowerShell
{
    [SPCmdlet(RequireUserFarmAdmin = true)]
    [Cmdlet("Set", "SPMSiteProvisioningSettings")]
    class SetSiteProvisioningSettingsCmdlet : SPCmdlet
    {
        [Parameter(Mandatory = true, ValueFromPipeline = true)]
        public SPWebApplicationPipeBind WebApplication { get; set; }

        [Parameter(Mandatory = true)]
        public string ActiveAuthenticationProvider { get; set; }
       

        [Parameter(Mandatory = true)]
        public string[] WebTemplates { get; set; }

        protected override void InternalBeginProcessing()
        {
            while (true)
            {
                SPWebApplication app = WebApplication.Read();
                bool updateRequired = false;
                SiteProvisioningSettings settings = app.GetSiteProvisioningSettings();
                
                if (this.ActiveAuthenticationProvider.Equals(settings.ActiveAuthenticationProvider) == false)
                {
                    settings.ActiveAuthenticationProvider = this.ActiveAuthenticationProvider;
                    updateRequired = true;
                }
                if ((this.WebTemplates.Except(settings.WebTemplates).Count() > 0) ||
                    (settings.WebTemplates.Except(this.WebTemplates).Count() > 0))
                {
                    settings.WebTemplates = this.WebTemplates;
                    updateRequired = true;
                }

                try
                {
                    if (updateRequired == true)
                    {

                        base.Host.UI.WriteLine(string.Format(null, "Updating site Provisioning Settings for {0}", app.GetResponseUri(SPUrlZone.Default)));
                        settings.Update();
                    }
                    break; // exit loop if update is successful
                }
                catch (SPUpdatedConcurrencyException)
                {
                    app = app.Clone() as SPWebApplication;
                }
            }
        } 
    }
}
